package com.jiangjun.fetch.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class ResponseSender {

	private static final String default_charset = "GBK";

	private static final String default_ContentType = "text/plain;charset=";

	public static void sendGzipResponse(HttpServletResponse response, byte[] res, String charset, String contentType) {
		ServletOutputStream o = null;
		GZIPOutputStream out = null;
		if (charset != null && !"".equalsIgnoreCase(charset)) {
		} else {
			charset = default_charset;
		}
		if (contentType != null && !"".equalsIgnoreCase(contentType)) {
		} else {
			contentType = default_ContentType;
		}
		response.setCharacterEncoding(charset);
		response.setContentType(contentType + charset);
		// cmwap下不能带Content-Encoding,需要关闭Content-Encoding标记，并使用私有协议替换
		response.setHeader("Content-Encoding", "GZIP");
		response.setHeader("Connection", "keep-alive");
		// logger.info("response :" + new String(res));
		try {
			o = response.getOutputStream();
			out = new GZIPOutputStream(o);
			out.write(res);
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (out != null) {
					out.flush();
					out.finish();
					out.close();
				}
				if (o != null) {
					o.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void sendResponse(HttpServletResponse response, byte[] res, String charset, String contentType) {
		ServletOutputStream o = null;
		if (charset != null && !"".equalsIgnoreCase(charset)) {
		} else {
			charset = default_charset;
		}
		if (contentType != null && !"".equalsIgnoreCase(contentType)) {
		} else {
			contentType = default_ContentType;
		}
		response.setCharacterEncoding(charset);
		response.setContentType(contentType + charset);
		response.setHeader("Connection", "keep-alive");
		// logger.info("response :" + new String(res));
		try {
			o = response.getOutputStream();
			o.write(res);
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (o != null) {
					o.flush();
					o.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
